package com.example.boot.http.consumer.client;

import com.example.boot.http.consumer.bean.User;
import com.example.boot.http.consumer.common.Result;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"rawtypes"})
public class BootXMLClient {

    private static final String PREFIX_URL = "http://localhost:8090/boot/provider/xml";

    public static void main(String[] args) throws JAXBException {
        BootXMLClient bootXMLClient = new BootXMLClient();
        System.out.println("bootXMLClient.get ---> " + bootXMLClient.get(1));
        User user = new User("boot-xml", 15);
        System.out.println("bootXMLClient.add ---> " + bootXMLClient.add(user));
    }

    public User add(User user) throws JAXBException {
        String urlString = PREFIX_URL + "/add";
        String resultString = new RestTemplate().exchange(urlString, HttpMethod.POST,
                new HttpEntity<>(user, null), String.class).getBody();
        Result result = xmlToResult(resultString);
        return (User) result.getData();
    }

    public User get(Integer id) throws JAXBException {
        Map<String, Integer> uriVariables = new HashMap<>();
        uriVariables.put("id", id);
        String urlString = PREFIX_URL + "/get/{id}";
        String resultString = new RestTemplate().exchange(urlString, HttpMethod.GET,
                new HttpEntity<>(null, null), String.class, uriVariables).getBody();
        Result result = xmlToResult(resultString);
        return (User) result.getData();
    }

    private Result xmlToResult(String xml) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(Result.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (Result) unmarshaller.unmarshal(new StringReader(xml));
    }

}
